<template>
	<view :class="['page',{'iphoneX':isIphoneX}]">
		<template v-if="isLogin">
			<view class="body">
				<view class="form-wrap m-b2">
					<view class="map">
						<map style="width: 100%; height: 400rpx;" :polyline="polylines" scale="16"
							:latitude="params.latitude" :longitude="params.longitude" :markers="markers"
							:circles="circles">
						</map>
						<cover-view class="get-local-btn" @click="getLocal">
							<cover-image class="local-img" src="@/static/images/get_local_icon.png"></cover-image>
						</cover-view>
					</view>
					<view class="form-item">
						<view class="label">防控地址：</view>
						<view class="form-input">
							<template v-if="params.address">
								<view class="content">
									<textarea class="inp" auto-height disabled v-model="params.address"
										placeholder="获取位置中..." maxlength="-1"></textarea>
								</view>
							</template>
							<template v-else>
								<view class="content" @click="getLocal">
									<textarea class="inp" auto-height disabled v-model="params.address"
										placeholder="获取位置中..." maxlength="-1"></textarea>
									<view class="icon">
										<view class="iconfont f-s42 f-blue">&#xe648;</view>
									</view>
								</view>
							</template>
						</view>
					</view>

					<view class="form-item" v-if="params.address">
						<view class="label">经纬度：</view>
						<view class="form-input">
							<view class="content">
								<input type="text" class="inp" v-model="params.location" disabled placeholder="输入经纬度" />
							</view>
						</view>
					</view>

					<view class="form-item">
						<view class="label">选择生境类型：</view>
						<template v-if="params.envtype">
							<picker class="form-picker" mode="selector" :range="envtypes" @change="changeEnvtypes">
								<view class="picker">
									<input type="text" class="select-data t-l" v-model="params.envtype"
										placeholder="选择生境类型" disabled>
									<view class="icon">
										<view class="iconfont f-s68">&#xeb8a;</view>
									</view>
								</view>
							</picker>
						</template>
						<template v-else>
							<view class="form-input">
								<view class="content">
									<input type="text" class="inp" v-model="params.envtype" placeholder="输入生境类型" />
								</view>
							</view>
						</template>
					</view>


					<view class="form-item">
						<view class="label">防控面积：</view>
						<view class="form-input">
							<view class="content">
								<input type="digit" class="inp" v-model="params.fk_area" placeholder="输入防控面积" />
								<view class="link">亩</view>
							</view>
						</view>
					</view>

					<view class="form-item">
						<view class="label">药剂用量：</view>
						<view class="form-input">
							<view class="content">
								<input type="digit" class="inp" v-model="params.bait_count" placeholder="输入药剂用量" />
								<view class="link">公斤</view>
							</view>
						</view>
					</view>

					<view class="form-item">
						<view class="label">扑杀蚁巢数：</view>
						<view class="form-input">
							<view class="content">
								<input type="number" class="inp" v-model="params.kill_count"
									placeholder="输入扑杀蚁巢数(选填)" />
								<view class="link">个</view>
							</view>
						</view>
					</view>



				</view>

				<!-- 图片上传 -->
				<view class="form-wrap m-b2">
					<view class="upload-pic-item">
						<view class="label">现场照片</view>
						<view class="form-upload-pic">
							<template>
								<view class="img-item" v-for="(item,index) in params.files" :key="index">
									<image src="@/static/images/filter_bg.png" mode="widthFix">
										<!-- 占位 -->
									</image>
									<view class="img-wrap" @click="previewPic(index)">
										<image class="img" :src="item.status==1?$imgPath(item.file_path):item.url"
											mode="widthFix"></image>
									</view>
									<view class="del-icon" @click="delPic(index)">
										<view class="iconfont">&#xe74b;</view>
									</view>
									<view v-if="item.status==0" class="loading-img">
										<div class="loading-icon loader-18"></div>
									</view>
								</view>
							</template>
							<view class="img-item add-btn" @click="uploadImage">
								<image src="@/static/images/upload_pic.png" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>

				<view class="form-wrap m-b2">
					<view class="form-textarea-item">
						<view class="label a-t">备注信息</view>
						<view class="form-textarea">
							<textarea class="inp-textarea" v-model="params.remark" placeholder="备注信息(选填),如地块名称等"
								maxlength="-1"></textarea>
						</view>
					</view>
				</view>

			</view>

			<!-- 底部 -->
			<view class="footer">
				<view class="fix-wrap bottom">
					<view class="btn" @click="submit">提交</view>
				</view>
			</view>


		</template>
	</view>
</template>

<script>
	import {
		dateFormat,
		uploadImage,
		previewImage,
		uploadToServe,
		d2Dms
	} from '@/common/util.js'
	import {
		gd_map_Key,
		gd_map_Key_web
	} from '@/config.js'
	export default {
		name: 'name',
		data() {
			return {
				isLogin: true,
				isIphoneX: getApp().globalData.isIphoneX,
				userInfo: uni.getStorageSync('userInfo'),
				isStop: true,
				envtypes: [],
				catch_local: uni.getStorageSync('local'),
				isSaveData: false, // 是否保存上次数据
				prev_data: {},
				params: {
					location: '',
					latitude: '',
					longitude: '',
					fid: 0,
					address: '',
					envtype: '' || uni.getStorageSync('fk_data').env_type,
					fk_area: "",
					bait_count: '',
					kill_count: '',
					files: [],
					remark: '' || uni.getStorageSync('fk_data').remark,
					weather: '',
					temperature: '',
					humidity: '',
					altitude: '',
					speed: '',
					accuracy: '',
					prevlongitude: '',
					prevlatitude: ''
				},
				marker_id: 1,
				markers: [],
				circles: [{
					latitude: '',
					longitude: '',
					color: "#ff00000A",
					fillColor: "#ff00003A",
					radius: "50"
				}],
				polylines: [{
					points: [],
					color: "#fcd535",
					width: 10
				}],
			}


		},
		async onLoad() {
			this.isLogin = await this.$loginState('check');

			this.prev_data = uni.getStorageSync('prev_yfk_' + this.params.pid); // 上次未提交数据 
			if (this.isLogin) {
				this.getUserInfo();
				this.getLocal();
				this.getEnvtype();

				if (this.prev_data) {
					let _this = this;
					uni.showModal({
						content: '有未提交的作业，是否继续上一次作业',
						success(res) { 
							if(res.confirm){
								_this.params.fk_area=_this.prev_data.fk_area;
								_this.params.bait_count=_this.prev_data.bait_count;
								_this.params.files=_this.prev_data.files;
								_this.params.kill_count=_this.prev_data.kill_count;
								_this.params.fid=_this.prev_data.fid;
							}else{
								uni.removeStorageSync('prev_yfk_'+_this.params.pid); 
							}		 
						}
					})
				}

			}
		},
		async onShow() {
			// 10s获取1次位置
			this.timer = setInterval(() => {
				this.updateLocus();
			}, 10000)

		},
		onHide() { 
			if(!this.isSaveData&&(this.params.fk_area||this.params.bait_count||this.params.kill_count||this.params.files.length>0)){ 
				uni.setStorage({
					key: 'prev_yfk_' + this.params.pid,
					data: {
						fk_area: this.params.fk_area,
						bait_count: this.params.bait_count,
						files: this.params.files,
						kill_count: this.params.kill_count,
						fid: this.params.fid
					}
				})
			}
			clearInterval(this.timer); // 关闭轮询位置定时器
		},
		onUnload() { 
			if(!this.isSaveData&&(this.params.fk_area||this.params.bait_count||this.params.kill_count||this.params.files.length>0)){ 
				uni.setStorage({
					key: 'prev_yfk_' + this.params.pid,
					data: {
						fk_area: this.params.fk_area,
						bait_count: this.params.bait_count,
						files: this.params.files,
						kill_count: this.params.kill_count,
						fid: this.params.fid
					}
				})
			}
			clearInterval(this.timer); // 关闭轮询位置定时器
		},
		methods: {

			// 获取用户信息
			getUserInfo: async function() {
				let res = await this.$api.user_api.getUserInfo();
				if (res.data.ret == 0) {
					this.userInfo = res.data.data;
				}
			},


			// 获取当前位置
			getLocal: function() {

				let _this = this;
				uni.showLoading({
					title: "获取位置中..."
				})
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					altitude: true,
					accuracy: 50,
					success: function(res) {
						uni.hideLoading();
						let lat = d2Dms(parseFloat(res.longitude).toFixed(6)); // d2Dms方法 转为度分秒格式
						let lng = d2Dms(parseFloat(res.latitude).toFixed(6)); // d2Dms方法 转为度分秒格式
						_this.params.location = lat + '，' + lng;
						_this.params.latitude = res.latitude;
						_this.params.longitude = res.longitude;
						_this.params.altitude = res.altitude;
						_this.params.speed = res.speed;
						_this.params.accuracy = res.accuracy;

						_this.circles[0].latitude = _this.params.latitude;
						_this.circles[0].longitude = _this.params.longitude;

						_this.markers[0] = {
							id: 0,
							latitude: parseFloat(_this.params.latitude),
							longitude: parseFloat(_this.params.longitude),
							iconPath: '/static/images/my_local.png',
						}

						_this.getCityInfo(res.latitude, res.longitude); // 根据坐标获取城市信息

						uni.setStorage({
							key: 'local',
							data: {
								latitude: _this.params.latitude,
								longitude: _this.params.longitude
							}
						})

						//  判断是否相同地址范围 设置位置偏差
						let difx = Math.abs(_this.catch_local.longitude - res.longitude.toFixed(6));
						let dify = Math.abs(_this.catch_local.latitude - res.latitude.toFixed(6));

						if (!_this.catch_local || difx > 0.1 || dify > 0.1) {
							_this.addLocus();

						}
					},
					fail() {
						uni.hideLoading();
						uni.showToast({
							icon: "none",
							title: '获取位置失败',
							mask: true,
							duration: 2000,
							success() {}
						})
					}
				});
			},

			// 更新轨迹点
			updateLocus: function() {
				let _this = this;
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					altitude: true,
					highAccuracyExpireTime: 5000,
					accuracy: 50,
					success: function(res) {

						//  判断是否相同地址范围 设置位置偏差
						let difx = Math.abs(_this.params.prevlongitude - res.longitude);
						let dify = Math.abs(_this.params.prevlatitude - res.latitude);

						if (res.accuracy <= 30) {
							if ((_this.params.prevlongitude == '' || _this.params.prevlatitude == '') || (
									difx > 0.00005 && difx < 0.0035) || (dify > 0.00005 && dify <
									0.0035)) {
								console.log('位置变化')
								_this.params.accuracy = res.accuracy;
								_this.params.latitude = res.latitude;
								_this.params.longitude = res.longitude;
								_this.params.speed = res.speed;
								_this.params.altitude = res.altitude;

								_this.circles[0].latitude = _this.params.latitude;
								_this.circles[0].longitude = _this.params.longitude;

								_this.markers[0] = {
									id: 0,
									latitude: parseFloat(res.latitude),
									longitude: parseFloat(res.longitude),
									iconPath: '/static/images/my_local.png',
								}

								let local = {
									latitude: parseFloat(res.latitude),
									longitude: parseFloat(res.longitude),
								}
								_this.polylines[0].points.push(local);

								_this.addLocus();
							}
						} else {
							console.log('无效点')
							clearInterval(_this.timer);
							setTimeout(() => {
								// 10s获取1次位置
								_this.timer = setInterval(() => {
									_this.updateLocus();
								}, 10000)
							}, 500)

						}
					}
				});
			},

			// 选择位置
			chooseAgress: function() {
				let _this = this;
				uni.chooseLocation({
					latitude: this.params.latitude,
					longitude: this.params.longitude,
					success: function(res) {
						_this.params.latitude = res.latitude;
						_this.params.longitude = res.longitude;

						_this.getCityInfo(res.latitude, res.longitude); //  获取新地址城市信息
					}
				})
			},

			//获取天气信息
			getWeatherInfo: async function(adcode) {
				let res = await this.$api.yfk_api.getWeather({
					key: gd_map_Key_web,
					city: adcode
				})
				if (res != false && res.data.info == "OK") {
					if (res.data.lives.length > 0) {
						this.params.weather = res.data.lives[0].weather;
						this.params.temperature = res.data.lives[0].temperature;
						this.params.humidity = res.data.lives[0].humidity;
					}
				}

			},

			// 获取城市信息
			getCityInfo: async function(lat, lng) {
				let res = await this.$api.yfk_api.getCityInfo({
					key: gd_map_Key_web,
					location: lng + ',' + lat
				})
				if (res.data.status == 1) {
					this.loading = false;
					this.params.address = res.data.regeocode.formatted_address;
					this.getWeatherInfo(res.data.regeocode.addressComponent.adcode); // 根据adcode 获取天气信息

				}
			},

			// 获取生境类型
			getEnvtype: async function() {
				let res = await this.$api.yfk_api.getEnvtype();
				if (res.data.ret == 0) {
					res.data.data.envtypes.push('其他')
					this.envtypes = res.data.data.envtypes;
					if (!uni.getStorageSync('fk_data').env_type) {
						this.params.envtype = res.data.data.envtypes[0];
					}
				}
			},

			// 上传图片
			uploadImage: function() {
				// 上传现场照片
				let _this = this;

				let params = {
					lat: this.params.latitude,
					lng: this.params.longitude,
					location: this.params.location,
					address: this.params.address,
					weather: this.params.weather
				};
				// JSON.parse(decodeURIComponent(option.item));
				params = encodeURIComponent(JSON.stringify(params));
				uni.navigateTo({
					url: '/package_common/photograph/photograph?params=' + params,
					animationType: 'none'
				})


				// uploadImage({
				// 	length: _this.params.files.length,
				// 	maxSize: 1,
				// 	sourceType:['camera'],
				// 	success(res) {  
				// 		let params_data = {};
				// 		params_data.status = 0;
				// 		params_data.url = res.tempFilePaths[0];
				// 		_this.params.files.push(params_data); 
				// 		uploadToServe({
				// 			url: '/yfk/upload-file',
				// 			filePath: res.tempFilePaths[0],
				// 			name: 'photo',
				// 			formData: {
				// 				'p_id': 0,
				// 				'uid': _this.userInfo.id
				// 			}
				// 		}).then((up_res) => { 
				// 			if (up_res.ret == 0) {								
				// 				params_data.file_name = up_res.data.file_name;
				// 				params_data.file_path = up_res.data.file_path;
				// 				params_data.file_type = up_res.data.file_type;
				// 				params_data.status = up_res.data.status;
				// 				params_data.type = up_res.data.type; 								
				// 			}
				// 		}).catch((err)=>{
				// 			console.log(err)
				// 		})
				// 	}
				// })
			},

			//上传临时图片
			upload_tpimg() {
				let params_data = {},
					_this = this;
				params_data.url = getApp().globalData.upload_img;
				params_data.status = 0;
				this.params.files.push(params_data);
				console.log('upload-img', params_data.url);
				uploadToServe({
					url: '/yfk/upload-file',
					filePath: params_data.url,
					name: 'photo',
					formData: {
						'p_id': 0,
						'uid': _this.userInfo.id
					}
				}).then((up_res) => {
					if (up_res.ret == 0) {
						params_data.file_name = up_res.data.file_name;
						params_data.file_path = up_res.data.file_path;
						params_data.file_type = up_res.data.file_type;
						params_data.status = up_res.data.status;
						params_data.type = up_res.data.type;
					}
				}).catch((err) => {
					console.log(err)
				})
			},

			// 预览图片
			previewPic: function(index) {
				let _this = this;
				let preview_data = [];
				this.params.files.forEach(item => {
					preview_data.push(item.url);
				})
				previewImage({
					data: preview_data,
					index: index
				})
			},

			// 删除图片
			delPic: async function(index) {
				let res = await this.$api.ycj_api.deletefile({
					file_path: this.params.files[index].file_path
				})
				if (res.data.ret == 0) {
					this.params.files.splice(index, 1);
				}
			},


			// 切换生境
			changeEnvtypes: function(e) {
				if (e.detail.value == this.envtypes.length - 1) {
					this.params.envtype = '';
				} else {
					this.params.envtype = this.envtypes[e.detail.value];
				}
			},

			// 提交数据
			submit: async function() {
				let _this = this;

				if (this.params.envtype == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入生境类型',
						mask: true,
						duration: 1000
					})
					return
				};
				if (this.userInfo.is_nx != 1 || !this.is_active_area) {
					if (this.params.fk_area == '') {
						uni.showToast({
							icon: 'none',
							title: '请输入防控面积',
							mask: true,
							duration: 1000
						})
						return
					};
					if (this.params.bait_count == '') {
						uni.showToast({
							icon: 'none',
							title: '请输入药剂用量',
							mask: true,
							duration: 1000
						})
						return
					};
				}

				if (this.params.files.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '请上传现场照片',
						mask: true,
						duration: 1000
					})
					return
				};

				let img_status = this.params.files.some(item => {
					if (item.status == 0) {
						return true
					}
				})

				if (img_status) {
					uni.showToast({
						icon: 'none',
						title: '图片未上传完',
						mask: true,
						duration: 1000
					})
					return
				}

				if (this.isStop) {
					this.isStop = false;
					let res = await this.$api.yfk_api.addFkData({
						'files': JSON.stringify(this.params.files),
						'fid': this.params.fid,
						'gcj02_lat': this.params.latitude,
						'gcj02_lng': this.params.longitude,
						'address': this.params.address,
						'env_type': this.params.envtype,
						'fk_area': this.params.fk_area, // 活动推广项目/常规项目
						'bait_count': this.params.bait_count,
						'kill_count': this.params.kill_count, // 活动推广项目/常规项目
						'create_uid': this.userInfo.id,
						'weather': this.params.weather,
						'temperature': this.params.temperature,
						'humidity': this.params.humidity,
						'altitude': this.params.altitude,
						'remark': this.params.remark,
					});
					uni.showLoading({ 
						title: "数据提交中...",
						mask: true
					})   
					if (res.data.ret == 0) {
						_this.updateCollectData(); 
						this.params.fid = 0; 
						setTimeout(()=>{
							uni.showToast({
								icon:"success",
								title: "数据提交成功",
								mask: true,
								duration: 1000,
								success() {
									_this.isSaveData=true;
									setTimeout(() => {
										_this.isStop = true;
										uni.navigateBack({
											delta:1
										})
									}, 1100)
									
									uni.removeStorageSync('prev_yfk_'+_this.params.pid);   // 清除上次数据
									
									uni.setStorage({
										key:'fk_data',
										data:{
											env_type: _this.params.envtype,
											remark: _this.params.remark
										}
									})						
								}
							})
						},1000)	 
					} else {
						uni.hideLoading();
						uni.showToast({
							image: '../../static/images/error.png',
							title: res.data.message,
							mask: true,
							duration: 1000,
							success() {
								setTimeout(() => {
									_this.isStop = true;
								})
							}
						})
					}

				}
			},

			//上传轨迹信息
			addLocus: async function() {
				let _this = this;
				uni.setKeepScreenOn({
					keepScreenOn: true
				});
				let res = await this.$api.yfk_api.addLocus({
					'uid': this.userInfo.id,
					'fid': this.params.fid,
					'speed': (this.params.speed).toFixed(2),
					'accuracy': (this.params.accuracy).toFixed(2),
					'gcj02_lat': this.params.latitude,
					'gcj02_lng': this.params.longitude, 
				}); 
				if(res.data.ret==0){
					this.params.prevlongitude=this.params.longitude;
					this.params.prevlatitude=this.params.latitude;
					if (this.params.fid == 0 && res.data.data > 0  && !this.prev_data.fid) { 
						this.params.fid = res.data.data;
					}
				}
			},

			//更新数据 
			updateCollectData: async function () {
			    let _this = this;	
				let updateState=0;	
				 
				
			    //更新地区代码W
				let res=await this.$api.yfk_api.adCode(); 
				if(res.data.ret==0){ 
					updateState+=1;
				} 

				//添加用户轨迹 
				let addLocusUrl = await this.$api.yfk_api.addUserLocus({
					'uid': this.userInfo.id,
					'date': dateFormat('YYYY-mm-dd', new Date())
				});

				if (addLocusUrl.data.ret == 0) {
					updateState += 1;
				}  

				//添加项目用户的监测点到mongodb
				setTimeout(async () => {
					let addMarkerUrl = await _this.$api.yfk_api.addMarkers({ 
						'createUid': parseInt(_this.userInfo.id)
					});

					if (addMarkerUrl.data.ret == 0) {
						updateState += 1;
					}  
					
					if(addMarkerUrl.data.ret==0){ 
						updateState+=1;
					}  

				}, 800); 
					 
			},

		},
		components: {},

		computed: {
			isUpload() {
				return this.$store.state.upload_state
			}
		},
		watch: {
			isUpload(newVal, oldVal) {
				if (newVal) {
					console.log('开始上传图片');
					this.$store.commit('UPDATE_UPLOAD_STATE', false);
					this.upload_tpimg();
				}
			}
		}

	}
</script>

<style lang="less">
	.form-wrap .label {
		width: 35%;
	}

	.form-wrap .content .link {
		color: #000;
	}

	.status {
		padding: 0 20rpx;
		color: #f00;
		font-size: 28rpx;
	}

	.btn {
		@h: 80rpx;
		width: 98%;
		margin: 10rpx auto;
		text-align: center;
		height: @h;
		line-height: @h;
		background: linear-gradient(#e96b5c, #ce3c2f);
		border-radius: 10rpx;
		color: #fff;
		font-size: 34rpx;
	}

	.prev-btn {
		text-align: right;
		padding: 20rpx;

		text {
			padding: 4rpx 15rpx;
			background: #ff9600;
			border-radius: 8rpx;
			color: #fff;
			font-size: 32rpx;
		}
	}

	.prev-data {
		padding: 18rpx 10rpx;
		background: #f5f5f5;
		text-align: right;
		color: #999;
		font-size: 28rpx;

		.val {
			color: #333;
		}

		.use-btn {
			color: #d03c30;
		}
	}
</style>
